<template>
  <div class="index-container">
    <div class="header_active">
      <img src="@/assets/images/activeheader.png" alt="" class='headerimage'>
    </div>
    <div class="activebody ">
      <div class="flexcolumn bodybg">
        <!-- <img src="@/assets/images/body_whitebg.png" alt="" class="postiion_img"> -->
        <div class="detailinfo">填写详细信息</div>
        <van-form class="loginboxform mt_10"  @submit="onSubmit">
          <!-- 地区 -->
          <van-field clickable name="area" :value="value" label="" placeholder="点击选择省市区" class="mb_10" @click="showArea = true" />
          <van-popup v-model="showArea" position="bottom">
            <van-cascader
                v-model="cascaderValue"
                title="请选择所在地区"
                :options="options"
                :field-names="fieldNames"
                @close="showArea = false"
                @change="onChange"
                @finish="onFinish"
              />
            <!-- <van-area :area-list="areaList" @confirm="onConfirm(1,$event)" @cancel="showArea = false" /> -->
          </van-popup>
          <van-field v-model="form.title" label="" :rules="[{ required: true, message: '请输入活动标题' }]" @blur="checkTitle" class="mb_10" placeholder="请输入活动标题" />
          <span class="f_12" v-if="titlecode!=1" style="color:red;display:block;margin-top:-10px">该活动已被收集</span>
          <!-- {pattern:/^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\*\+,;=.]+$/, message:'请输入正确的活动链接'} -->
          <van-field v-model="form.url" label="" :rules="[{ required: true, message: '请输入活动链接' }]" @blur="checkLink" class="" placeholder="请输入活动链接" />
          <span class="f_12" v-if="linkcode!=1" style="color:red">该活动已被收集</span>
          <span class="f_14 disblock mb_10" style="color:#7E7E7E">活动链接，请填写投票活动的主页链接！</span>
          <!--  :default-date="defaultDate" @closed='onCloseCalendar' -->
          <van-field clickable name="calendar" :value="date" label="" placeholder="点击选择日期" class="mb_10" @click="showCalendar = true" />
          <van-calendar v-model="showCalendar" type="range" :min-date="minDate" @confirm="onConfirmCalendar" />
          
          <div v-for="(item,index) in form.co_sponsor" class="flexcenter mb_10" :key="index" style="align-items:flex-start" >
            <van-field  v-model="form.co_sponsor[index].value" label="" :rules="[{ required: true, message: '请输入主办方' }]" class="" placeholder="请输入主办方" />
            <van-icon v-if="index==0" name="add-o" class='add_icon' @click="addSponsor"/>
            <van-icon v-if="index!==0" name="clear" class='add_icon delicon' @click="delSponsor(index,item)"/>
          </div>

          <van-field v-model="form.sponsor" label="" class="mb_10" placeholder="请输入协办方" />
          <div class="flexend" style='margin-bottom:10px'>
            <!-- <van-button icon="plus" size="small" @click="addContact"/> -->
            <div class="iconaddbtn" @click="addContact"><van-icon name="plus" />添加</div>
          </div>
          <div v-for="(item,index) in form.contacts" class="flexcenter contactslink" :key="index+'111'" >
            <van-field v-model="form.contacts[index].username" label=""  class="mb_20" placeholder="请输入联系人" />
            <van-field v-model="form.contacts[index].phone" label=""  class="mb_20" placeholder="请输入联系方式" />
            <van-icon v-if="index!==0" name="clear" class='add_icon delicon f_16' @click="delcontact(index,item)"/>
          </div>

          <van-field v-model="form.active_class" name="picker" label="" :rules="[{ required: true, message: '请选择活动类型' }]" placeholder="请选择活动类型" class="mb_10" @click="showClass = true"  />
          <van-popup v-model="showClass" position="bottom">
              <van-picker show-toolbar :columns="classList" value-key="value" @confirm="onConfirm(3,$event)" @cancel="showClass = false" />
          </van-popup>

          <!--  -->
          <van-field v-model="form.active_level" name="picker" label="" :rules="[{ required: true, message: '请选择活动级别' }]" placeholder="请选择活动级别" class="mb_10" @click="showPicker = true"  />
          <van-popup v-model="showPicker" position="bottom">
              <van-picker show-toolbar :columns="levelList" value-key="value" @confirm="onConfirm(2,$event)" @cancel="showPicker = false" />
          </van-popup>

          <!-- <van-field v-model="form.num" label="" :rules="[{ required: true, message: '请输入活动总票数' }]" class="mb_10" placeholder="请输入活动总票数" /> -->

          <span class="flexcenter c_7e7 f_13">感谢您的填写，审核通过后，您将获得{{coin}}元</span>
          <div class="flexcenter flexcolumn">
            <van-button class="loadbtn" native-type="submit">
              <van-loading v-if='loading' type="spinner" size="16px" color="#fff" style="display:inline-block"/> 
              <span class="logintext"> 提 交 </span>
            </van-button>
            <div class="loadbtn canclebtn" @click="cancle">取 消</div>
          </div>
        </van-form>
      </div>
    </div>
  </div>
</template>

<script>
import { getUserData,getData } from '@/api/home';
import { getCitys, getRegions} from '@/api/comm';
import { areaList } from '@vant/area-data';
import { levelList,levelName,levelId } from '@/api/datalist';
import { subTask,checkUrl,checkTitle } from '@/api/task';
export default {
  data() {
    const start = new Date()
    start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
    return {
      coin:0,
      loading:false,
      value:'',
      show:false,
      showArea:false,
      showPicker:false,
      showCalendar:false,
      showClass:false,
      areaList,
      form:{
        active_level:'',
        active_class:'',
        startime:'',
        endtime:'',
        co_sponsor:[{value:''}],
        contacts:[{username:'',phone:''}],
        title:'',
        url:'',
        // num:'',
      },
      minDate:new Date(2000, 0, 1),
      date:'',
      levelList,
      classList:[],
      cascaderValue:'',
      options:[],
      fieldNames:{
        text: 'name',
        value: 'id',
      },
      defaultDate:[start,new Date()],
      linkcode:1,
      titlecode:1
    }
  },

  created(){
    // 获取城市
    this.getProvince();
    this.getDicts('/task/index/active_class').then(res=>{
      this.classList = res.data.map(item=>({...item,value:item.name}));
    });
    this.getData();
  },
  methods: {
    getProvince(){
      this.getDicts('/task/index/province').then(res=>{
        this.options = res.data.map(item=>{
            if(item.name!=='全国'){
              item.children = [];
            }
            return item;
          });
      });
    },

    onChange(item){
      let selectArr = item.selectedOptions;
      let val = item.value;
      selectArr.forEach((item,index)=>{
        if(index==0){
          this.form.province = item.name;
        }
        if(index==1){
          this.form.city = item.name;
        }
        if(index==2){
          this.form.area = item.name;
        }
      });
      // console.log('123123',selectArr);
      // this.cascaderValue=selectArr.map((option) => option.name).join('/');
      this.value=selectArr.map((option) => option.name).join('/');
      if(selectArr.length ==1&&selectArr[0].class == 1){
        getCitys({province_index:val}).then(res=>{
          // this.options = res.data;
          let data = res.data.map(item=>({...item,children:[]}))
          this.options.forEach((item,index)=>{
            if(val == item.id&&selectArr[0].name!=='全国'){
              this.options[index].children = data
            }
          })
        });
      }
      if(selectArr.length ==2 && selectArr[1].class == 2){
        getRegions({city_index:val}).then(res=>{
          // this.region = res.data;
          let parentId = selectArr[0].id;
          // let childrenId = selectArr[1].id;
          this.options.forEach((item,index)=>{
            if(parentId == item.id){
              item.children.forEach((citem,cindex)=>{
                if(val == citem.id){
                  this.options[index].children[cindex].children = res.data;
                }
              })
            }
          })
        })
      }

    },

    onFinish(val){
      console.log('完成',val);
      // let name = '';
      val.selectedOptions.forEach((item,index)=>{
        // name = name+item.name;
        if(index==0){
          this.form.province = item.name;
        }
        if(index==1){
          this.form.city = item.name;
        }
        if(index==2){
          this.form.area = item.name;
        }
      });
      console.log('name:',this.form.province,this.form.city,this.form.area);
      // this.cascaderValue=val.selectedOptions.map((option) => option.name).join('/');
      this.value=val.selectedOptions.map((option) => option.name).join('/');
      this.showArea = false;
      // this.val.selectedOptions.map((option) => option.text).join('/');
    },

    // getProvince(){
    //   if(type==1){ //省份
    //     this.getDicts('/task/index/province').then(res=>{
    //       this.province = res.data;
    //     });
    //   }
    //   if(type==2){ //城市
    //     getCitys(params).then(res=>{
    //       this.citys = res.data;
    //     })
    //   }
    //   if(type==3){ //地区
    //     getRegions(params).then(res=>{
    //       this.region = res.data;
    //     })
    //   }
    // },

    getData(){
      getData().then(res=>{
        if(res.code == 1){
          this.coin = res.data.coin;
        }
      })
    },

    goPage(page){
      this.$router.push({name:page})
    },

    addSponsor(){
      this.form.co_sponsor.push({value:''})
    },

    delSponsor(index,item){
      this.form.co_sponsor.splice(index,1)
    },

    addContact(){
      this.form.contacts.push({username:'',phone:''})
    },

    delcontact(index,item){
      this.form.contacts.splice(index,1)
    },

    onConfirm(type,val){
      console.log('type:',type,val);
      if(type == 1){
        this.value = val[0].name+'-'+val[1].name+'-'+val[2].name;
        this.form.province = val[0].name;
        this.form.city = val[1].name;
        this.form.area = val[2].name;
        this.showArea = false;
      }
      if(type == 2){
        this.form.active_level=val.value;
        this.showPicker=false;
      }
      if(type == 3){
        this.form.active_class=val.value;
        this.showClass=false;
      }
      
    },
    
    onCloseCalendar(){
      this.defaultDate=this.defaultDate;
      this.showCalendar = false; 
    },

    // 日期
    onConfirmCalendar(date){
      const [start, end] = date;
      this.defaultDate = [start,end];
      this.showCalendar = false;
      console.log('start, end:',this.parseTime(start,'{y}-{m}-{d}'), end);
      this.date = this.parseTime(start,'{y}-{m}-{d}')+'/'+this.parseTime(end,'{y}-{m}-{d}');
      this.form.startime = this.parseTime(start,'{y}-{m}-{d}');
      this.form.endtime = this.parseTime(end,'{y}-{m}-{d}');
    },

    className(val){
      let valname= '';
      this.classList.forEach(item=>{
        if(val == item.name){
          valname = item.id
        }
      })
      return valname
    },

    checkUrl(){
      return checkUrl({url:this.form.url,})
    },

    checkTitle(){
      if(!this.form.title) return;
      checkTitle({title:this.form.title}).then(res=>{
        this.titlecode = 1;
      }).catch(e=>{
        this.titlecode = 0;
      })
    },

    checkLink(){
      if(!this.form.url) return;
      checkUrl({url:this.form.url}).then(res=>{
        this.linkcode = 1;
      }).catch(e=>{
        this.linkcode = 0;
      })
    },

    onSubmit(){
        if(this.linkcode==0||this.titlecode==0) return; //链接相同不给过
        let flag = true;
        this.form.contacts.forEach(item=>{
          if((item.username&&!item.phone)||(!item.username&&item.phone)){
            this.$toast('联系人与联系电话需要都填上哟~');
            flag = false;
          }
        })
        if(!flag) return;
        let params = {
          province:this.form.province,
          city:this.form.city,
          area:this.form.area,
          contacts:this.form.contacts,
          sponsor:this.form.sponsor,
          startime:this.form.startime,
          endtime:this.form.endtime,
          title:this.form.title,
          url:this.form.url,
          // num:this.form.num,
        };
        params.co_sponsor = this.form.co_sponsor.map(item=>item.value);
        params.active_class = this.className(this.form.active_class);
        params.active_level = levelId(this.form.active_level)
        // console.log('params.active_class:',params.active_class,params.active_level);
        this.loading = true;
        // checkUrl({url:this.form.url}).then(res=>{
        //   if(res.code == 1){
            subTask(params).then(res=>{
              if(res.code == 1){
                this.$toast('添加成功');
                this.resetFrom();
              }
              this.loading = false;
            }).catch(()=>{
              this.loading = false;
            })
          // }
        // }).catch(()=>{
        //   this.loading = false;
        // })
        // if(res.code==1){
          
        // }else{
        //   this.$toast('该活动已存在');
        // }
        
    //     this.$store.dispatch('user/login',this.form).then(res=>{
    //         this.$router.push({ path: "/" });
    //         // }else{
    //         //     console.log('失败',res.msg);
    //         //     this.$toast(res.msg);
    //         // }
    //         this.loading = false;
    //     }).catch(e=>{
    //         this.loading = false;
    //     })
    },

    cancle(){
      this.$router.back();
    },

    resetFrom(){
      this.cascaderValue='';
      this.form.active_level='';
      this.form.active_class='';
      this.form.province='';
      this.form.city='';
      this.form.area='';
      this.form.contacts=[{username:'',phone:''}];
      this.form.co_sponsor=[{value:''}];
      this.form.startime='';
      this.form.endtime='';
      this.form.sponsor='';
      this.form.url='';
      this.form.title='';
      this.form.num='';
      this.date='';
      this.value=''
    }

  }
}
</script>

<style lang="scss" scoped>
.index-container {
  width: 100%;
  min-height: 100vh;
  background:url("~@/assets/images/activebg.png") center no-repeat;
  background-size: cover;
  position: relative;
}
.header_active{
  height: 360px;
  width: 100%;
}
.activebody{
  width: 100%;
  padding: 30px;
  padding-bottom: 0;
  min-height: calc(100vh - 360px);
}
.headerimage{
  width: 100%;
  height: 100%;
}
.bodybg{
  background: url('~@/assets/images/body_whitebg.png') center no-repeat;
  background-size: contain;
  background-size:100% 100%;
  // background-attachment:fixed;
  min-height: calc(100vh - 420px);
  padding:30px;
  // padding-bottom: 0;
  position: relative;
}
// .postiion_img{
//   position: absolute;
//   top: 0;
//   bottom: 0;
//   width: 100%;
// }
.detailinfo{
  width: 466px;
  height: 86px;
  background:url('~@/assets/images/activebtn.png') center no-repeat;
  background-size: contain;
  margin:0 auto;
  margin-top: -20px;
  color: white;
  text-align: center;
  line-height: 80px;
  font-size: 40px;
}
.add_icon{
 display: inline-block;
 margin-left: 12px; 
 line-height: 70px;
}
.delicon{
  color: red;
}
.iconaddbtn{
  border: 1px solid #1989fa;
  font-size: 28px;
  padding: 10px 20px;
  color: #1989fa;
  border-radius: 10px;
}
.loadbtn{
    margin-top: 60px;
    width: 220px;
    height: 80px;
    background: url('~@/assets/images/activebtnsub.png') center no-repeat ;
    background-size: contain;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 30px;
    border: 0;
    color: #000;
}

.canclebtn{
  background: #fff;
  border: 1px solid #727272;
  color: #747474;
  border-radius: 16px;
  margin-top: 30px;
  margin-bottom: 30px;
}
</style>
<style lang="scss">
.contactslink{
  .van-cell{
    overflow: inherit;
  }
  .van-field__value{
    overflow: inherit;
    position:relative;
    .van-field__error-message{
      position:absolute;
      bottom:-40px
    }
  }
}
.loginboxform{
    .van-cell{
        padding: 0;
        background-color: transparent;
    }
    .van-field__body{
        background-color: white;
        padding: 10px 32px;
        border-radius: 12px;
        border: 1px solid #eee;
    }
    .van-field__control{
        // border: 1px solid #000;
    }
    .van-cell::after{
        border: 0;
    }
    .van-field__error-message{
        padding-left:32px;
    }
    .fileformitem{
        .van-field__body{
            padding: 0;
            border: 0;
        }
    }
    .van-button::before{
        background-color:transparent;
        border: 0;
    }
}

</style>